package com.xiao.wiki.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import com.xiao.wiki.domain.User;
import com.xiao.wiki.domain.UserExample;
import com.xiao.wiki.exception.BusinessException;
import com.xiao.wiki.exception.BusinessExceptionCode;
import com.xiao.wiki.mapper.UserMapper;
import com.xiao.wiki.req.UserLoginReq;
import com.xiao.wiki.req.UserQueryReq;
import com.xiao.wiki.req.UserResetPasswordReq;
import com.xiao.wiki.req.UserSaveReq;
import com.xiao.wiki.resp.UserLoginResp;
import com.xiao.wiki.resp.UserQueryResp;
import com.xiao.wiki.resp.PageResp;
import com.xiao.wiki.util.CopyUtil;
import com.xiao.wiki.util.RequestContext;
import com.xiao.wiki.util.SnowFlake;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author ：降蓝
 * @description：TODO
 * @date ：2021/11/13 21:32
 */
@Service
public class UserService {

    private static final Logger LOG = LoggerFactory.getLogger(UserService.class);

    @Resource
    private UserMapper userMapper;

    @Resource
    private SnowFlake snowFlake;

    public PageResp<UserQueryResp> list(UserQueryReq req) {
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
       if(!ObjectUtils.isEmpty(req.getLoginName()))
        {
            criteria.andLoginNameEqualTo(  req.getLoginName() );

        }

        // 从数据库查询数据
        PageHelper.startPage(req.getPage(),req.getSize());
        List<User> userList = userMapper.selectByExample(userExample);

        PageInfo<User> userPageInfo = new PageInfo<>(userList);
        LOG.info("总行数：{}",userPageInfo.getTotal());
        LOG.info("总页数：{}",userPageInfo.getPages());


        PageResp<UserQueryResp> pageResp = new PageResp();
        // 将数据转换为响应需要的字段
        List<UserQueryResp> userResps = CopyUtil.copyList(userList, UserQueryResp.class);
        pageResp.setTotal(userPageInfo.getTotal());
        pageResp.setList(userResps);
        return pageResp;
    }

    /**
     * 保存
     */
    public void save(UserSaveReq req) {
        User user = CopyUtil.copy(req, User.class);
        if (ObjectUtils.isEmpty(req.getId())) {
            User userDB = selectByLoginName(req.getLoginName());
            if (ObjectUtils.isEmpty(userDB)){
                //  新增
                user.setId(snowFlake.nextId());
                userMapper.insert(user);
            } else {
                //  用户名已存在
                throw new BusinessException(BusinessExceptionCode.USER_LOGIN_NAME_EXIST);
            }
        } else {
            //  更新
            user.setLoginName(null);
            userMapper.updateByPrimaryKeySelective(user);
        }
    }

    /**
     * 删除
     */
    public void delete(Long id) {
            userMapper.deleteByPrimaryKey(id);
    }

    public User selectByLoginName(String LoginName){
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        criteria.andLoginNameEqualTo(LoginName);
        List<User> userList = userMapper.selectByExample(userExample);
        if (CollectionUtils.isEmpty(userList)){
            return null;
        } else {
            return userList.get(0);
        }
    }

    /**
     * 修改密码
     */
    public void resetPassword(UserResetPasswordReq req) {
        User user = CopyUtil.copy(req, User.class);
        userMapper.updateByPrimaryKeySelective(user);
    }

    /**
     * 登录
     */
    public UserLoginResp login(UserLoginReq req) {
        // IP地址

        User userDb = selectByLoginName(req.getLoginName());

        if (ObjectUtils.isEmpty(userDb)) {
            // 用户名不存在
            LOG.info("用户名不存在，{}",req.getLoginName());
            throw new BusinessException(BusinessExceptionCode.LOGIN_USER_ERROR);
        } else {
            if (userDb.getPassword().equals(req.getPassword())) {
                //  登录成功
                final UserLoginResp userLoginResp = CopyUtil.copy(userDb, UserLoginResp.class);
                userDb.setIpAddress(RequestContext.getRemoteAddr());
                userLoginResp.setIpAddress(RequestContext.getRemoteAddr());
                userMapper.updateByPrimaryKeySelective(userDb);
                return userLoginResp;
            } else {
                //  密码错误
                LOG.info("密码错误，{}",req.getLoginName());
                throw new BusinessException(BusinessExceptionCode.LOGIN_USER_ERROR);
            }
        }
    }


}
